import  fcgi.Request;
import  fcgi.Connection;

import 
	tango.time.Clock;


int main (char[][] args)
{
    FastCGIConnection connection = new FastCGIConnection ("", "1983");
    FastCGIRequest request = new FastCGIRequest(connection);
    int counter = 0;

    auto Stdout = new vBuffer(1024, 1024);// new FormatOutput!(char) (request.stdout)
    while ( request.accept () )
    {
	Stdout.clear;
	scope now = Clock.now ;
	scope(exit){
		Stdout("line:")(__LINE__)(" all use:")( (Clock.now-now).millis )("ms\n") ;
	}
        Stdout ("Content-type: text/html\r\n\r\n") ("<head><title>My first page</title></head>");
        Stdout ("<body>");
        Stdout ("<h1> Hello world </h1><br>") ("Request #") (++counter) ("<br><br>\n");
	
	Stdout("line:")(__LINE__)(" use:")( (Clock.now-now).millis )("ms\n") ;
        // Write IP
        auto ip = ("REMOTE_ADDR" in request.args);
        if (ip)
            Stdout ("Your IP is ") (*ip) ("<br><br>\n");
        else
            Stdout ("Cannot extract IP :(<br><br>\n");

	Stdout("line:")(__LINE__)(" use:")( (Clock.now-now).millis )("ms\n") ;
	
        // Write stdin
        Stdout ("Data: \"");
        while (1)
        {
            char[10] string;
            int rd = request.stdin.read(string);
            if (rd > 0)
                Stdout(string[0 .. rd]);
            if (rd != string.length)
            {
                Stdout ("\"<br><br>");
                break;
            }
        }
	Stdout("line:")(__LINE__)(" use:")( (Clock.now-now).millis )("ms\n") ;
	
        // Write all
        Stdout ("\nEnvironment:<br>");
        foreach (key, value; request.args)
        {
            Stdout ("request.args[\"")(key) ("\"] = \"") (value) ("\"<br>\n");
        }

        Stdout ("</body>\n");
	request.stdout.write(Stdout.slice);
        request.exitStatus = 0;
    }

    return request.exitStatus;
}
